<template>
  <div class="refund-container">
    <!-- 使用导航栏组件 -->
    <NavHeader title="申请售后" @back="goBack" />
    
    <!-- 订单信息 -->
    <div class="order-info card" v-if="order">
      <div class="order-header">
        <div class="order-id">订单号: {{ order.orderNo }}</div>
        <div class="order-status">{{ getOrderStatusText(order.status) }}</div>
      </div>
      
      <div class="order-content">
        <div class="order-image">
          <img :src="order.image" :alt="order.productName" />
        </div>
        <div class="order-details">
          <h4 class="order-product">{{ order.productName }}</h4>
          <p class="order-price">x{{ order.specCount }} ${{ formatNumber(order.payAmount) }} {{ order.currency }}</p>
          <div class="order-date" style="margin-top: 10px;">
            <van-icon name="clock-o" />
            <span>{{ order.updatedAt }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 售后表单 -->
    <div class="refund-form card">
      <van-form @submit="onSubmit">
        <!-- 售后类型 -->
        <van-field
          name="type"
          label="售后类型"
          :rules="[{ required: true, message: '请选择售后类型' }]"
        >
          <template #input>
            <van-radio-group v-model="formData.type" direction="horizontal">
              <van-radio name="1">退货退款</van-radio>
              <van-radio name="2">其他原因</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        
        <!-- 售后原因 -->
        <van-field
          v-model="formData.reason"
          name="reason"
          label="售后原因"
          placeholder="请选择售后原因"
          readonly
          clickable
          :rules="[{ required: true, message: '请选择售后原因' }]"
          @click="showReasonPicker = true"
        />
        <van-action-sheet
          v-model:show="showReasonPicker"
          :actions="reasonActions"
          cancel-text="取消"
          close-on-click-action
          @select="onSelectReason"
        />
        
        <!-- 问题描述 -->
        <van-field
          v-model="formData.description"
          name="description"
          label="问题描述"
          type="textarea"
          placeholder="请详细描述您遇到的问题"
          :rules="[{ required: true, message: '请描述您遇到的问题' }]"
          rows="3"
          autosize
        />
        
        <!-- 上传图片 -->
        <div class="upload-images">
          <div class="upload-label">上传凭证</div>
          <van-uploader
            v-model="formData.images"
            multiple
            :max-count="5"
            :after-read="afterRead"
          />
          <div class="upload-tip">最多上传5张图片，每张不超过5MB</div>
        </div>
        
        <!-- 联系方式 -->
        <van-field
          v-model="formData.contact"
          name="contact"
          label="联系方式"
          placeholder="请输入您的联系方式"
          :rules="[{ required: true, message: '请输入联系方式' }]"
        />
        
        <!-- 提交按钮 -->
        <div class="submit-btn">
          <van-button round block type="primary" native-type="submit" :loading="submitting">
            提交申请
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showLoadingToast } from 'vant'
import { getOrderDetail } from '@/api/order'
import { applyRefund } from '@/api/order'
import { getOrderStatusText } from '@/utils/orderStatus'
import { formatNumber } from '@/utils/utils'
import { uploadFile } from '@/api/file'
import NavHeader from '@/components/NavHeader.vue'

const router = useRouter()
const route = useRoute()
const orderId = route.query.orderId

// 订单信息
const order = ref(null)
const submitting = ref(false)
const showReasonPicker = ref(false)

// 售后原因选项 - 使用ActionSheet格式
const reasonActions = [
  { name: '商品质量问题' },
  { name: '商品与描述不符' },
  { name: '收到商品破损' },
  { name: '商品缺少配件' },
  { name: '发错商品' },
  { name: '不想要了' },
  { name: '其他原因' }
]

// 表单数据
const formData = reactive({
  type: '1', // 默认退货退款
  reason: '',
  description: '',
  images: [],
  contact: ''
})

// 获取订单详情
const fetchOrderDetail = async () => {
  if (!orderId) {
    showToast('订单ID不能为空')
    goBack()
    return
  }
  
  try {
    const res = await getOrderDetail(orderId)
    if (res.code === 0 && res.data) {
      order.value = res.data
      
      // 自动填充联系方式（如果订单中有的话）
      if (res.data.contact) {
        formData.contact = res.data.contact
      }
    } else {
      showToast(res.message || '获取订单详情失败')
      goBack()
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    showToast('获取订单详情失败，请稍后重试')
    goBack()
  }
}

// 返回上一页
const goBack = () => {
  // 判断来源页面
  const fromOrderDetail = route.query.from === 'detail'
  
  if (fromOrderDetail) {
    // 如果是从订单详情页来的，返回订单详情页
    router.back()
  } else {
    // 否则返回订单列表页
    router.replace('/orders')
  }
}

// 选择售后原因
const onSelectReason = (action) => {
  formData.reason = action.name
}

// 上传图片后的处理
const afterRead = async (file) => {
  // 检查文件大小
  if (file.file.size > 5 * 1024 * 1024) {
    showToast('图片大小不能超过5MB')
    return
  }
  
  // 设置上传状态
  file.status = 'uploading';
  file.message = '上传中...';
  
  try {
    // 调用上传API，传递file.file作为参数
    const res = await uploadFile(file.file);
    if (res.code === 0) {
      // 上传成功
      file.status = 'done';
      file.message = '上传成功';
      file.url = res.data.url || '';
      //console.log('上传成功:', res.data);
    } else {
      // 上传失败
      file.status = 'failed';
      file.message = '上传失败';
      showToast(res.message || '上传失败');
    }
  } catch (error) {
    // 处理异常
    console.error('上传图片异常:', error);
    file.status = 'failed';
    file.message = '上传失败';
    showToast('上传失败，请稍后重试');
  }
}

// 提交售后申请
const onSubmit = async () => {
  submitting.value = true
  showLoadingToast({
    message: '提交中...',
    forbidClick: true,
  })
  
  try {
    // 处理图片数据，只获取成功上传的图片URL，并以逗号分隔
    const imageUrls = formData.images
      .filter(img => img.status === 'done')
      .map(img => img.url)
      .join(',')

    console.log("sssss",imageUrls);
    
    const res = await applyRefund({
      orderId: parseInt(orderId),
      refundType: formData.type,
      title: formData.reason,
      remark: formData.description,
      images: imageUrls,
      tel: formData.contact
    })
    
    if (res.code === 0) {
      showToast('售后申请提交成功')
      
      // 延迟返回到订单详情页
      setTimeout(() => {
        // 跳转回订单详情页
        router.replace(`/order/${orderId}`)
      }, 1500)
    } else {
      showToast(res.message || '提交失败')
    }
  } catch (error) {
    console.error('提交售后申请失败:', error)
    showToast('提交失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 组件挂载时获取订单详情
onMounted(() => {
  fetchOrderDetail()
  
  // 检查是否有返回路径参数
  if (!route.query.returnPath && !route.query.from) {
    console.log('未指定返回路径，将使用默认返回逻辑')
  }
})
</script>

<style scoped>
.refund-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 20px;
  padding-top: 54px; /* 为导航栏留出空间 */
}

.card {
  background-color: #ffffff;
  border-radius: 8px;
  margin: 12px;
  padding: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.order-id {
  font-size: 14px;
  color: #666;
}

.order-status {
  font-size: 14px;
  color: #ff6b00;
}

.order-content {
  display: flex;
}

.order-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 12px;
}

.order-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.order-product {
  font-size: 15px;
  margin: 0 0 8px;
  font-weight: normal;
}

.order-price {
  font-size: 16px;
  color: #f44336;
  margin: 0;
}

.upload-images {
  padding: 16px 16px 0;
}

.upload-label {
  margin-bottom: 8px;
  font-size: 14px;
  color: #646566;
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #969799;
}

.submit-btn {
  margin: 24px 16px;
}
</style>